package io.gitee.zhangbinhub.acp.cloud.oauth.controller

import cn.dev33.satoken.annotation.SaCheckPermission
import cn.dev33.satoken.context.SaHolder
import cn.dev33.satoken.oauth2.data.model.AccessTokenModel
import cn.dev33.satoken.oauth2.processor.SaOAuth2ServerProcessor
import cn.dev33.satoken.stp.StpUtil
import com.fasterxml.jackson.databind.ObjectMapper
import io.gitee.zhangbinhub.acp.cloud.oauth.vo.TokenUserInfoVo
import io.gitee.zhangbinhub.acp.cloud.resource.server.constant.AcpCloudResourceServerConstant
import io.gitee.zhangbinhub.acp.cloud.resource.server.tools.TokenTools
import io.swagger.v3.oas.annotations.Operation
import jodd.util.Base64
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class AuthController(private val objectMapper: ObjectMapper) {
    // OAuth2-Server 端：处理所有 OAuth2 相关请求
    @RequestMapping("/oauth/*")
    fun request(): Any {
        println("------- 进入请求: " + SaHolder.getRequest().url)
        return SaOAuth2ServerProcessor.instance.dister()
    }
    @Operation(summary = "获取当前用户token信息", description = "根据当前登录的用户token值，返回详细信息")
    @GetMapping(value = ["/token-info"], produces = [MediaType.APPLICATION_JSON_VALUE])
    fun currToken(): ResponseEntity<AccessTokenModel> =
        ResponseEntity.ok(TokenTools.getAccessTokenModel())

    @Operation(summary = "测试权限")
    @SaCheckPermission("test-info")
    @GetMapping(value = ["/test-info"], produces = [MediaType.APPLICATION_JSON_VALUE])
    fun testInfo(): ResponseEntity<AccessTokenModel> =
        ResponseEntity.ok(TokenTools.getAccessTokenModel())

    @Operation(summary = "获取当前用户token存储的信息")
    @GetMapping(value = ["/token-store"], produces = [MediaType.APPLICATION_JSON_VALUE])
    fun tokenStoreInfo(): ResponseEntity<AccessTokenModel> =
        ResponseEntity.ok(TokenTools.getAccessTokenModel().apply {
            val permissionList = StpUtil.getPermissionList()
            val roleList = StpUtil.getRoleList()
            println(roleList)
            println(permissionList)
            println(StpUtil.getTokenInfo().toString())
            Base64.decode(this!!.extraData[AcpCloudResourceServerConstant.TOKEN_CLAIMS_USER_INFO].toString()).let {
                objectMapper.readValue(it, TokenUserInfoVo::class.java)
            }.let {
                println(it)
            }
        })
}